<template>
  <view class="page-container">
    <HeaderBar
        title="直通车详情"
        @click="pageBack"
        :navBarBgc="navBarBgc"
    ></HeaderBar>
    <view class="product-name">{{yudingData.routeName}}-{{trafficInfo.name}}</view>
    <view class="page-content">
      <view class="reservation-module-title">
        <i class="iconfont icon-yuyuejilu1"></i>
        <text class="title">预约选择</text>
        <image class="border-img" src="http://img.jowong.com/aba/2025-03-27/图层 554_1743061625989.png"></image>
      </view>
      <view class="first-title">使用日期</view>
      <!--  使用日期选择  -->
      <view class="ticket-choose-date-container">
        <view
            v-for="(item,index) in dateList"
            :key="index"
            @click="chooseDateId(item.date)"
            :class="['date-item',item.date === chooseDate ? 'active-date-item' : '']"
        >
          <view>{{item.title}}</view>
          <view>{{item.label}}</view>
        </view>
        <view class="more-date flex flex-center flex-1" @click="open">
			<wd-calendar v-model="value" :min-date="minDate" @confirm="handleConfirm">
			  <view class="left-container">
				<view>更多</view>
				<view>日期</view>
			  </view>
			</wd-calendar>
          <wd-icon name="arrow-right" size="18px" color="#181818"></wd-icon>
        </view>
      </view>
      <view class="first-title">车型</view>
      <!--   车型选择   -->
      <view class="car-type-container">
        <view
            v-for="(item,index) in trafficInfo.carModels"
            :key="index"
            @click="chooseCar(item,index)"
            :class="['car-type-item','mb30','mr20',index === choiceCarTypeId ? 'active' : '']"
        >
          {{getName(item.code)}}({{item.seats}})座
        </view>
      </view>
      <view class="first-title">发车时间</view>
      <!--  发车时间列表    -->
      <view class="car-type-container">
        <view
            v-for="(item,index) in timeSlotList"
            :key="index"
			@click="!isTimePassed(item) && chooseTime(item, index)"
            :class="['car-type-item','mb30','mr20',index === choiceCarTimeId ? 'active' : '',isTimePassed(item) ? 'disabled' : '']"
        >
          <text class="pr10 start-time">{{item}} - 发车</text>
        </view>
      </view>
      <view class="first-title">上车地点</view>
      <!--  上车地点    -->
      <view class="car-Route-container">
        <view 
            v-for="(item,index) in carRoute"
            :key="index"
            @click="chooseRoute(item,index)"
            :class="['car-type-item','mb30',index === choiceRouteId ? 'active' : '']"
        > {{ item.address }} </view>
      </view>
    </view>
    <view class="bottom-container">
      <view class="buyer-notice-container">
        <view class="buyer-notice-content">无需取票 I 有条件退</view>
        <view class="buyer-notice-tip">购买须知></view>
      </view>
      <view class="top-container flex ">
        <view class="price">￥ {{yudingData.trafficInfodetail.price}}</view>
        <view class="right-container">
          <!-- <view class="price-detail-tip">
            <text>明细</text>
            <wd-icon name="arrow-down" size="22px"></wd-icon>
          </view> -->
          <view class="btn" @click="gotoReserve">去预定</view>
        </view>
      </view>
      <view class="safe-content" :style="{height:bottomSafeInsetNumber + 'px'}"></view>
    </view>
  </view>
</template>

<script setup>
import dayjs from "dayjs";
import {commonWordList} from "@/api/system";
import {onLoad} from "@dcloudio/uni-app";
import HeaderBar from "@/trafficSubPack/components/headerBar/index.vue";
import {trafficDetail,trafficRoute} from "@/trafficSubPack/api/trafficHome"; 

const navBarBgc = "linear-gradient(180deg, rgba(186,209,194,1) 0%, rgba(207,223,212,1) 33%, rgba(230,238,233,1) 100%);";
const dateList = ref([]);
const startDate = ref(dayjs().format("YYYY-MM-DD"));
const chooseDate = ref(dayjs().format("YYYY-MM-DD"));
	const minDate =Date.now() 
const pageBack = () =>{
  uni.navigateBack()
} 
const value = ref(Date.now()) 
const trafficInfo = ref([])
const timeSlotList = ref([]);
const choiceCarTypeId = ref(0);
const choiceCarTimeId = ref();
const choiceRouteId = ref(0);
const bottomSafeInsetNumber = ref(0);

const yudingData =reactive({
  trafficInfo:[],
  chooseDate:chooseDate || '',
  trafficInfodetail:{},
  choiceCarTime:'',
  routeId:'',
  routeName:'',
  carModel:[],
  upLocationId: 0,
  upLocationName: "",
  upLocationAddress: "",
})
const carRoute = ref([])
const gettrafficDetail = (id)=>{
  trafficDetail(id).then(res=>{
    // console.log('trafficDetail',res);
    let {result} = res;

    trafficInfo.value = result
    if (result.carModels){
      timeSlotList.value = JSON.parse(result.carModels[0].departureTime)
      /*拼音？*/
      yudingData.trafficInfo = result
      yudingData.trafficInfodetail = result.carModels[0]
	  yudingData.upLocationId = carRoute.value[0].id
	  yudingData.upLocationName = carRoute.value[0].name
	  yudingData.upLocationAddress = carRoute.value[0].address
    }
  })
}
// 使用日期 
const chooseDateId = (data)=>{ 
  choiceCarTimeId.value = ''
  yudingData.choiceCarTime = ''
  chooseDate.value = data;
  yudingData.chooseDate = data  
  value.value = new Date(data).getTime()  
}
const isTimePassed = (timeStr) => {
  // console.log(timeStr,dayjs().format("YYYY-MM-DD"));
  if(yudingData.chooseDate != dayjs().format("YYYY-MM-DD")){
	return false
  } else {
	const [hours, minutes] = timeStr.split(":").map(Number);
	const now = new Date();
	const compareTime = new Date();
	compareTime.setHours(hours, minutes, 0, 0);
	return now > compareTime; 
  }
  
};
 
const queryCommonWordList = async () => {
	await commonWordList({keys:"CAT_MODEL_TRAFFIC"}).then(res => { 
		yudingData.carModel = res.result.CAT_MODEL_TRAFFIC
	}); 
}; 
const getName = (val)=>{
	return yudingData.carModel.find(item => item.code == val)?.name || '';
}  
// 车型
const chooseCar = (data,index)=>{
  choiceCarTimeId.value = ''
  yudingData.choiceCarTime = ''
  timeSlotList.value = JSON.parse(data.departureTime)
  trafficInfo.value.price = data.price
  choiceCarTypeId.value = index;
  yudingData.trafficInfodetail = data
}
// 发车时间
const chooseTime = (data,index)=>{
  choiceCarTimeId.value = index;
  yudingData.choiceCarTime = data 
}
// 上车地点
const chooseRoute = (data,index)=>{ 
	choiceRouteId.value = index;
	yudingData.upLocationId = data.id
	yudingData.upLocationName = data.name
	yudingData.upLocationAddress = data.address
}

const gotoReserve =()=>{
  // console.log('yudingData',yudingData);
  // 将 yudingData 转换为 JSON 字符串
  if(yudingData.choiceCarTime == '') {
	  uni.showToast({
	  	title:'未选择发车时间',
		icon:"error"
	  })
	  return ;
  }
  const yudingDataJson = JSON.stringify(yudingData);

  // 使用 encodeURIComponent 对 JSON 字符串进行编码
  const encodedYudingData = encodeURIComponent(yudingDataJson);

  // 跳转到目标页面并传递参数
  uni.navigateTo({
    url: `/trafficSubPack/pages/directCar/orderWrite?yudingData=${encodedYudingData}`
  });
}

const generateDateArray = (startDate, count) =>  {
  const dateArray = [];
  const weekDays = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
  const today = new Date(); // 当前日期 
  const todayStr = today.toISOString().split("T")[0]; // 格式化 YYYY-MM-DD 

  for (let i = 0; i < count; i++) {
    const dateObj = new Date(startDate);
    dateObj.setDate(dateObj.getDate() + i); // 计算每一天

    const year = dateObj.getFullYear();
    const month = dateObj.getMonth() + 1; // 月份从 0 开始
    const day = dateObj.getDate();
    const weekDay = weekDays[dateObj.getDay()];
    const dateStr = `${year}-${month.toString().padStart(2, "0")}-${day.toString().padStart(2, "0")}`;

    // 计算 title
    let title = weekDay;
    if (dateStr === todayStr) {
      title = "今天";
    } else {
      const tomorrow = new Date(today);
      tomorrow.setDate(today.getDate() + 1);
      if (dateStr === tomorrow.toISOString().split("T")[0]) {
        title = "明天";
      } else {
        const afterTomorrow = new Date(today);
        afterTomorrow.setDate(today.getDate() + 2);
        if (dateStr === afterTomorrow.toISOString().split("T")[0]) {
          title = "后天";
        }
      }
    }

    // 组装对象
    dateArray.push({
      label: `${month}月${day}日`,
      date: dateStr,
      title: title,
    });
  }
  dateList.value = dateArray;
}

function handleConfirm({ value }) {  
	// 将时间戳转换为 Date 对象
	let date = new Date(value); 
	// 提取年、月、日，并格式化为 YYYY-MM-DD
	let year = date.getFullYear(); // 获取年份
	let month = String(date.getMonth() + 1).padStart(2, '0'); // 获取月份并补零
	let day = String(date.getDate()).padStart(2, '0'); // 获取日期并补零
	const datetime = `${year}-${month}-${day}`; 
	chooseDateId(datetime)
	generateDateArray(datetime,4); 
} 
const getUpaddres =(id)=>{
	trafficRoute(id).then(res=>{
		console.log(res);
		carRoute.value = res.result;
	})
}
// onLoad 获取 URL 参数
onLoad((options) => {
  queryCommonWordList()
  // console.log(options);
  if(options){
    gettrafficDetail(options.id)
	getUpaddres(options.routeId)
    yudingData.routeId = options.routeId
    yudingData.routeName = options.name
  } 
  generateDateArray(startDate.value,4);
  bottomSafeInsetNumber.value = uni.getSystemInfoSync().safeAreaInsets.bottom;
});
</script>

<style lang="scss" scoped>
.page-container {
  width: 100%;
  min-height: 100vh;
  .product-name {
    font-size: 42rpx;
    padding: 50rpx 27rpx;
    font-weight: bold;
    background: linear-gradient(180deg, rgba(231,239,234,1) 0%, rgba(239,244,241,1) 15%, rgba(255,255,255,1) 100%);
  }
  .page-content {
    padding: 0 27.5rpx;
    .reservation-module-title {
      position: relative;
      width: auto;
      display: flex;
      align-items: flex-end;
      .icon-yuyuejilu1 {
        font-size: 36rpx;
        color: #1b9c61;
      }
      .title {
        font-size: 29rpx;
        font-weight: bold;
        color: #2B2B24;
      }
      .border-img {
        position: absolute;
        bottom: -6rpx;
        left: 0;
        width: 153rpx;
        height: 7rpx;
      }
    }
    .first-title {
      padding: 30rpx 0;
      font-size: 29rpx;
      font-weight: bold;
    }
    .ticket-choose-date-container {
      display: flex;
      justify-content: space-between;
      .date-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 166rpx;
        width: 20%;
        border-radius: 10.5rpx;
        font-size: 25rpx;
        margin-right: 14rpx;
        color: #181818;
        background: #EEF0DF;
        overflow: hidden;
      }
      .active-date-item {
        color: #FDFFEB;
        background: #1B9C61;
      }
      .more-date{
        font-size: 25rpx;
      }
    }
    .car-type-container {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      .car-type-item {
        font-size: 25rpx;
        padding: 16rpx 34rpx;
        border-radius: 10.5rpx;
        color: #2B2B24;
        background: #EEF0DF; 
	  
	    &.active {
	      background-color: #409EFF;
	      color: #fff;
	      border: none;
	    }
	  
	    &.disabled {
	      background-color: #eee;
	      color: #999;
	      pointer-events: none; // 禁止点击
	    }
	  }

    }
    .car-Route-container { 
      align-items: center; 
      .car-type-item {
        font-size: 25rpx;
        padding: 16rpx 34rpx;
        border-radius: 10.5rpx;
        color: #2B2B24;
        background: #EEF0DF; 
	  
	    &.active {
	      background-color: #409EFF;
	      color: #fff;
	      border: none;
	    }
	  
	    &.disabled {
	      background-color: #eee;
	      color: #999;
	      pointer-events: none; // 禁止点击
	    }
	  }

    }
  }
  .active{
    color: #FDFFEB !important;
    background:#1B9C61 !important;
  }
}
.bottom-container {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  background: #FDFFEB;
  .buyer-notice-container {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 25rpx;
    padding: 12rpx 30rpx 12rpx 30rpx;
    background: #eef0df;
    .buyer-notice-content {
      color: #2B2B24;
    }
    .buyer-notice-tip {
      color: #AA5413;
    }
  }
  .top-container {
    justify-content: space-between;
    align-items: center;
    padding: 32rpx 20rpx 0 59rpx;
    .price {
      font-size: 42rpx;
      font-weight: bold;
      color: #AA5413;
    }
    .right-container {
      display: flex;
      align-items: center;
      .price-detail-tip {
        display: flex;
        align-items: center;
        padding-right: 11rpx;
        text {
          font-size: 30rpx;
        }
      }
      .btn {
        border-radius: 10.5rpx;
        font-weight: bold;
        padding: 25rpx 32rpx;
        color: #FDFFEB;
        background: #AA5413;
      }
    }
  }
}
</style>
